# -*- coding: utf-8 -*-
# @Time    : 2019-01-11 14:23
# @Author  : jerry
# @FileName: __init__.py.py
# @Software: PyCharm Professional Edition
# @Version : python 3.6.2
from datetime import datetime
import json
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm import sessionmaker

from master import config
from .api import api as api_v1_bp

APP_DIR = os.path.dirname(__file__)

app = Flask(__name__)
app.register_blueprint(api_v1_bp, url_prefix='/mysense/platform/api/v1')
conf = app.config.from_object(config)

# 加载数据库ORM
db = SQLAlchemy(app, use_native_unicode='utf8')
DB_Session = sessionmaker(bind=db.engine)
session = DB_Session()

# 加载授权
auth = HTTPBasicAuth()


class AlchemyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj.__class__, DeclarativeMeta):
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                try:
                    if isinstance(data, datetime):
                        data = data.strftime('%Y-%m-%d %H:%M:%S')
                    json.dump(data)
                    fields[field] = data
                except TypeError:
                    fields[field] = None
            return fields
        return json.JSONEncoder.default(self, obj)


def convert_to_json_string(data):
    return json.dump(data, ensure_ascii=False, cls=AlchemyEncoder)


from . import route, config
from .models import *
